using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using Orbitone.MeetingRooms.Services;
using Orbitone.MeetingRooms.Services.Model;

namespace Orbitone.MeetingRooms.RoomFinder.UserControls
{
    public partial class UpdateCalendarItem : UserControl
    {
        public string LoginUsername { get; set; }

        public string EventId { get; set; }
        public string EventMailbox { get; set; }

        public List<MailboxModel> Rooms { get; set; }
        public IExchangeService ExchangeService { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            updated.Value = "false";
        }

        public void Update(DateTime StartDate, DateTime EndDate)
        {
            if (!string.IsNullOrEmpty(EventId))
            {
                AppointmentModel appointmentEntity = ExchangeService.GetAppointment(EventId, EventMailbox, StartDate, EndDate); 

                CalendarItem.CalendarItemModel = new CalendarItemModel
                                                     {
                                                         Id = EventId,
                                                         Mailbox = EventMailbox,
                                                         Rooms =
                                                             Rooms.Select(
                                                                 r =>
                                                                 new ListItem
                                                                     {Text = r.DisplayName, Value = r.EmailAddress}).
                                                             ToList(),
                                                         RoomEmail = EventMailbox,
                                                         StartTime = appointmentEntity.StartDate,
                                                         EndTime = appointmentEntity.EndDate,
                                                         Date = appointmentEntity.StartDate,
                                                         Subject = appointmentEntity.Subject,
                                                         UserId = appointmentEntity.UserId,
                                                         SubjectEnabled = true,
                                                         ValidationGroup = "updateItem",
                                                         Title = "Reservation",
                                                         TitleButton = "Update"
                                                     };

                updated.Value = "true";
            }
        }

        protected void DeleteEvent(object sender, EventArgs e)
        {
            CalendarItemModel calendarItem = CalendarItem.CalendarItemModel;
            ExchangeService.DeleteAppointment(calendarItem.Id, calendarItem.Mailbox);

            string date = calendarItem.StartTime.ToString("ddMMyyyy");
            Response.Redirect("Calendar.aspx?Date=" + date);
        }

        protected void UpdateEvent(object sender, EventArgs e)
        {
            CalendarItemModel calendarItem = CalendarItem.CalendarItemModel;
            var model = new CalendarEventModel
                            {
                                Id = calendarItem.Id,
                                StartDate = calendarItem.StartTime,
                                EndDate = calendarItem.EndTime,
                                Mailbox = calendarItem.RoomEmail,
                                Subject = calendarItem.Subject,
                                UserId = calendarItem.UserId,
                                UserName = LoginUsername,
                            };

            if (model.StartDate.CompareTo(DateTime.Now) < 0)
            {
                lblerror.Text = "Start date is in the past.";
                ErrorPanel.Visible = true;
                return;
            }
            if (model.StartDate.CompareTo(model.EndDate) >= 0)
            {
                lblerror.Text = "End date before or equal to start date, this is not a valid combination.";
                ErrorPanel.Visible = true;
                return;
            }

            List<AvailabilityModel> availability = ExchangeService.GetAvailability(Rooms, model.StartDate, model.EndDate,
                                                                                   30);
            IEnumerable<CalendarEventModel> evts = null;
            AvailabilityModel events =
                availability.Where(m => m.Mailbox.EmailAddress.Equals(model.Mailbox)).FirstOrDefault();
            if (events != null)
            {
                evts =
                    events.CalendarEvents.Where(
                        c => (c.Id != model.Id) && ((model.EndDate <= c.StartDate) || (model.StartDate >= c.EndDate)));
            }

            if (evts != null && evts.Count() < events.CalendarEvents.Where(c => c.Id != model.Id).Count())
            {
                lblerror.Text = "Can not update appointment, because of overlapping time";
                ErrorPanel.Visible = true;
            }
            else
            {
                ExchangeService.DeleteAppointment(calendarItem.Id, calendarItem.Mailbox);
                ExchangeService.SaveAppointment(model);

                string date = model.StartDate.ToString("ddMMyyyy");
                Response.Redirect("Calendar.aspx?Date=" + date);
            }
        }
    }
}